package applet.resource;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.net.URL;

import javax.imageio.ImageIO;

/** A horizontal strip of drawable images. */
public class Sprite1D {
	/** */
	private final String filename;
	/** */
	private final int frameCount;
	/** */
	private BufferedImage image;
	/** */
	private final int frameWidth;
	/** */
	private final int frameHeight;

	/**
	 * Create and load a new sprite with the given filename.
	 * 
	 * @param newFilename
	 *            - the name of the file to load.
	 * @param newFrameCount
	 *            - the number of frames.
	 */
	public Sprite1D(final String newFilename, final int newFrameCount) {
		filename = newFilename;
		frameCount = newFrameCount;

		image = null;
		try {
			URL url = Sprite2D.class.getResource("/sprites/" + newFilename);
			image = ImageIO.read(url);
		} catch (Exception e) {
			System.err.println("ERROR: Image file \"/sprites/" + newFilename
					+ "\" could not be found.");
		}

		frameWidth = image.getWidth(null) / newFrameCount;
		frameHeight = image.getHeight(null);
	}

	/** @return the name of the file. */
	public final String getFilename() {
		return filename;
	}

	/** @return the number of frames. */
	public final int getFrameCount() {
		return frameCount;
	}

	/** @return the image. */
	public final BufferedImage getImage() {
		return image;
	}

	/**
	 * Draws the given frame of the sprite to the given graphics target.
	 * 
	 * @param g
	 *            - the graphics target.
	 * @param frame
	 *            - the frame of the strip to draw.
	 * @param x
	 *            - the horizontal position in pixels.
	 * @param y
	 *            - the vertical position in pixels.
	 */
	public final void draw(final Graphics g, final int frame, final double x,
			final double y) {
		final double half = 0.5;
		g.drawImage(image.getSubimage(frame * frameWidth, 0, frameWidth,
				frameHeight), (int) (x + half), (int) (y + half), null);
	}

	/**
	 * Draws the given frame of the sprite to the given graphics target.
	 * 
	 * @param g
	 *            - the graphics target.
	 * @param frame
	 *            - the frame of the strip to draw.
	 * @param x
	 *            - the horizontal position in pixels.
	 * @param y
	 *            - the vertical position in pixels.
	 */
	public final void draw(final Graphics g, final int frame, final int x,
			final int y) {
		g.drawImage(image.getSubimage(frame * frameWidth, 0, frameWidth,
				frameHeight), x, y, null);
	}
}
